require 'rubygems'
require 'hpricot'
include ScraperHtml

class Category < ActiveRecord::Base
  before_create :clear_description
  before_update :clear_description

  acts_as_tree :order=>"sort_order desc",:counter_cache => 'children_count'
  has_many :products
  has_many :properties

  GEOMETRY_IMAGE_SIZE = "360"
  MEDIUM_IMAGE_SIZE = "250"
  THUMB_IMAGE_SIZE = "100"

  UNITS = [
    [ "台",   "1" ],
    [ "支",   "2" ],
    [ "副",   "3" ]
  ]

  file_column :image_url, :magick => {:geometry=>GEOMETRY_IMAGE_SIZE,
    :versions => { "thumb" => THUMB_IMAGE_SIZE,"medium" => MEDIUM_IMAGE_SIZE}
  }

  def name_for_select
    "-" * self.ancestors().size + ActionView::Helpers::TextHelper.truncate(self.name,10)
  end

  def self.collection_for_select
    json_arr = Array.new
    build_json(self.find(:all,:conditions=>["parent_id is null"]),json_arr)
    return json_arr
  end

  def self.build_json(categories,json_arr)
    categories.each { |c|
      if c.children.size > 0
        json_arr << [c.name_for_select,c.id.to_s]
        build_json(c.children,json_arr)
      else
        json_arr << [c.name_for_select,c.id.to_s]
      end
    }
  end

  def clear_description
    self.description = clean_tag(self.description) if self.description
  end

  def self.parent_cagegories
    self.find(:all,:conditions=>"parent_id is null")
  end

  def self.find_by_parent_and_brand(brand_id,parent_id)
    self.find_by_sql(["SELECT DISTINCT c.*
FROM products p, categories c, brands b,categories c2
WHERE p.brand_id = b.id
AND (p.category_id = c.id or (p.category_id = c2.id and c2.parent_id = c.id))
AND brand_id = ? and c.parent_id = ? order by c.sort_order desc",brand_id,parent_id])
  end
end
